package array;

/*
稀疏数组:
稀疏数组有三列，
第一行，行数，列数，需要记录的数的总数
第二行，i      j   val
...

*/
public class SparseArray {
    public static void main(String[] args) {
        //创建一个11*11的棋盘，转为稀疏数组
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[5][5] = 2;
        System.out.println("输出原始的棋盘");
        for (int[] row : chessArr1) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        int sum = 0;
        //遍历原数组，统计需要记录的值的个数
        for (int[] row : chessArr1) {
            for (int data : row) {
                if (data != 0) {
                    sum++;
                }
            }
        }

        //创建稀疏数组
        int[][] sparseArray = new int[sum + 1][3];
        sparseArray[0][0] = chessArr1.length;
        sparseArray[0][1] = chessArr1[0].length;
        sparseArray[0][2] = sum;
        int index = 1;
        //遍历原始数组，给稀疏数组赋值
        for (int i = 0; i < chessArr1.length; i++) {
            for (int j = 0; j < chessArr1[0].length; j++) {
                if (chessArr1[i][j] != 0) {
                    sparseArray[index][0] = i;
                    sparseArray[index][1] = j;
                    sparseArray[index][2] = chessArr1[i][j];
                    index++;
                }
            }
        }
        System.out.println("得到的稀疏数组~~~~~~~~");
        for (int[] data : sparseArray) {
            System.out.println(data[0] + "\t" + data[1] + "\t" + data[2]);
        }

        //将稀疏数组回复为原始的二维数组
        int [][] array=new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i=1;i<sparseArray.length;i++){
            array[sparseArray[i][0]][sparseArray[i][1]]=sparseArray[i][2];
        }
        System.out.println("回复后的棋盘为：");
        for (int [] row:array){
            for (int data:row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
    }

}
